<template>
  <div>
    <el-tree :data="menuData" size="mini" show-checkbox node-key="id" :props="defaultProps"
             style="width: 100%;padding-top:20px;" ref="menuTree" :render-content="renderContent"
             v-loading="menuLoading" element-loading-text="拼命加载中" :check-strictly="true"
             @check-change="handleMenuCheckChange">
    </el-tree>
    <div style="margin-bottom: 30px">
      <div style="float:left;padding-left:24px;padding-top:12px;padding-bottom:4px;">
        <el-checkbox v-model="checkAll" @change="handleCheckAll" :disabled="this.selectRole.id == null">
          <b>全选</b>
        </el-checkbox>
      </div>
      <div style="float:right;padding-right:15px;padding-top:4px;padding-bottom:4px;">
        <kt-button :label="$t('action.reset')" perms="sys:role:edit" type="primary" @click="resetSelection"
                   :disabled="this.selectRole.id == null"/>
        <kt-button :label="$t('action.submit')" perms="sys:role:edit" type="primary" @click="submitAuthForm"
                   :disabled="this.selectRole.id == null" :loading="authLoading"/>
      </div>
    </div>

  </div>
</template>

<script>
  import KtTable from "@/views/Core/KtTable"
  import KtButton from "@/views/Core/KtButton"
  import TableTreeColumn from '@/views/Core/TableTreeColumn'
  export default {
    components:{
      KtTable,
      KtButton,
      TableTreeColumn
    },
    name: "AssignPermissions",
    props:{
      role:{
        type:Object,
        required:true
      }
    },
    data(){
      return {
        authLoading: false,
        menuLoading: false,
        currentRoleMenus: [],
        menuData: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        checkAll: false,
        selectRole: {},
      }
    },
    methods:{
      // 获取数据
      findTreeData() {
        this.menuLoading = true;
        this.$api.menu.findMenuTree().then((res) => {
          this.menuData = res.data;
          this.menuLoading = false;
        })
      },

      // 角色选择改变监听
      handleRoleSelectChange(val) {
        if(val == null || val.val == null) {
          return
        }
        this.selectRole = val.val;
        this.$api.role.findRoleMenus({'roleId':val.val.id}).then((res) => {
          this.currentRoleMenus = res.data;
          this.$refs.menuTree.setCheckedNodes(res.data)
        })
      },

      // 全选操作
      handleCheckAll() {
        if(this.checkAll) {
          let allMenus = [];
          this.checkAllMenu(this.menuData, allMenus);
          this.$refs.menuTree.setCheckedNodes(allMenus)
        } else {
          let Un = [];
          this.checkUnnecessaryNode(this.menuData, Un);
          this.$refs.menuTree.setCheckedNodes(Un)
        }
      },

      // 递归全选
      checkAllMenu(menuData, allMenus) {
        menuData.forEach(menu => {
          allMenus.push(menu);
          if(menu.children) {
            this.checkAllMenu(menu.children, allMenus)
          }
        });
      },

      // 递归无需清空项
      checkUnnecessaryNode(menuData, allMenus) {
        menuData.forEach(menu => {
          if (menu.disabled) {
            allMenus.push(menu);
          }
          if(menu.children) {
            this.checkAllMenu(menu.children, allMenus)
          }
        });
      },


      // 树节点选择监听
      handleMenuCheckChange(data, check) {
        if(check) {
          // 节点选中时同步选中父节点
          let parentId = data.parentId;
          this.$refs.menuTree.setChecked(parentId, true, false)
        } else {
          // 节点取消选中时同步取消选中子节点
          if(data.children != null) {
            data.children.forEach(element => {
              this.$refs.menuTree.setChecked(element.id, false, false)
            });
          }
        }
      },

      // 重置选择
      resetSelection() {
        this.checkAll = false;
        this.$refs.menuTree.setCheckedNodes(this.currentRoleMenus)
      },

      // 角色菜单授权提交
      submitAuthForm() {
        let roleId = this.selectRole.id;
        if('admin' === this.selectRole.name) {
          this.$message({message: '超级管理员拥有所有菜单权限，不允许修改！', type: 'error'});
          return
        }
        this.authLoading = true;
        let checkedNodes = this.$refs.menuTree.getCheckedNodes(false, true);
        let roleMenus = [];
        for(let i=0, len=checkedNodes.length; i<len; i++) {
          let node = checkedNodes[i];
          // 公共权限不需要保存
          if (!node.disabled) {
            let roleMenu = { roleId:roleId, menuId:node.id };
            roleMenus.push(roleMenu)
          }
        }
        this.$api.role.saveRoleMenus(roleMenus).then((res) => {
          if(res.code === 200) {
            this.$message({message: '操作成功', type: 'success'})
          } else {
            this.$message({message: '操作失败, ' + res.msg, type: 'error'})
          }
          this.authLoading = false
        })
      },
      renderContent(h, { node, data, store }) {
        return (
          <div class="column-container">
          <span style="text-algin:center;margin-right:80px;">{data.name}</span>
          <span style="text-algin:center;margin-right:80px;">
          <el-tag type={data.type === 0?'':data.type === 1?'success':'info'} size="small">
          {data.type === 0?'目录':data.type === 1?'菜单':'按钮'}
          </el-tag>
          </span>
          <span style="text-algin:center;margin-right:80px;"> <i class={data.icon}></i></span>
        <span style="text-algin:center;margin-right:80px;">{data.parentName?data.parentName:'顶级菜单'}</span>
          <span style="text-algin:center;margin-right:80px;">{data.url?data.url:'\t'}</span>
          </div>);
      },
    },
    watch:{
      role(){
        this.handleRoleSelectChange(this.role);
        this.checkAll = false;
      }
    },
    mounted() {
      this.findTreeData();
      this.handleRoleSelectChange(this.role);
    }
  }

</script>

<style scoped>

</style>
